#include "stdafx.h"
#ifdef LIT_OGRE_SUPPORT
#include <LitOgreState.h>
#include <LitInitialiser.h>
#include <LitRoot.h>

namespace Lit
{
	OgreState::OgreState( const String &name, OgreRenderWindowPtr window ) 
		: Initialiser("OgreState['"+name+"']")
		, mDetails(window)
	{}
	OgreState::OgreState( const OgreState &rk )
		: mDetails(rk.mDetails)
		, Initialiser(rk){}
	OgreState::~OgreState(){}
		
	OgreState& OgreState::operator=( const OgreState &rk ){ mDetails=rk.mDetails; return *this;}
	
	OgreDetails& OgreState::details(){ return mDetails; }
	const OgreDetails& OgreState::details() const{ return mDetails; }

	OgreInitialState::OgreInitialState( const String & cam_name, OgreRenderWindowPtr window ) 
		: OgreState("EngineReady", window)
		, mCameraName( cam_name )
	{}
	OgreInitialState::OgreInitialState( const OgreInitialState &rk )
		: OgreState(rk)
		, mCameraName( rk.mCameraName )
	{}
	OgreInitialState::~OgreInitialState(){}
		
	OgreInitialState& OgreInitialState::operator=( const OgreInitialState &rk ){ return *this;}
		
	bool OgreInitialState::renderOneFrame( float dt ){
		return true;
	}
	
	void OgreInitialState::createScene( ){		
		mDetails.setSceneManager( Ogre::Root::getSingletonPtr()->createSceneManager(Ogre::ST_GENERIC) );
		mDetails.setCamera( mDetails.sceneManager()->createCamera(mCameraName) );
 
		// Position it at 500 in Z direction
		mDetails.camera()->setPosition(Ogre::Vector3(0,0,80));
		// Look back along -Z
		mDetails.camera()->lookAt(Ogre::Vector3(0,0,-300));
		mDetails.camera()->setNearClipDistance(5);

		createViewport( mDetails.camera(), 0 );

		Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
		Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	}
	void OgreInitialState::destroyScene(){
		mDetails.window()->removeViewport(0);
		mDetails.sceneManager()->destroyCamera( mCameraName );
		Ogre::Root::getSingletonPtr()->destroySceneManager( *mDetails.sceneManager() );
	}
	void OgreInitialState::createViewport( OgreCameraPtr cam, int zOrder, float left, float top, float width, float height ){
		ApplicationSettings& sets(Lit::Root::Instance().getSettings());
		
		Ogre::ColourValue bg(sets.getOgreProperty<Ogre::ColourValue>("Viewports.Background",Ogre::ColourValue::ZERO));

		Ogre::Viewport* vp = mDetails.window()->addViewport(*cam,zOrder, left, top, width, height);
		vp->setBackgroundColour(bg);

		Ogre::Real compRatio = Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight());
		Ogre::Real ratio = sets.getOgreProperty<Ogre::Real>("Viewports.Ratio",compRatio);
		if( ratio == 0.0f || ratio == -1.0f ) mDetails.camera()->setAspectRatio(compRatio);		
		else mDetails.camera()->setAspectRatio(ratio);		
	}
};
#endif